#!/usr/bin/env python
# -*- coding: utf-8 -*-
#  content_card.py
#  description

#  Created by zhouzongli633 on 2020/8/17 11:03 上午.
#  Copyright ©Intellectus All rights reserved.
import json

from Common.logger import app_log
from Common.response import resp
from EducationContent.models import CardAttributes


def card_function(params, funct):
    if (('post_id' in params and params['post_id']) and
            ('feed_id' in params and params['feed_id']) and
            ('milestone_id' in params and params['milestone_id'])):
        return resp(400, {'error': 'Unauthorized'})
    row = CardAttributes.objects.filter(user_id=params['user_id'], feed_id=params['feed_id'], post_id=params['post_id'],
                                        milestone_id=params['milestone_id'], card_attribute=funct)
    if not row:
        row = CardAttributes(
            user_id=params['user_id'], feed_id=params['feed_id'], post_id=params['post_id'],
            milestone_id=params['milestone_id'], card_attribute=funct
        )
        row.save()
    return resp(0, row.card_attributes_to_json())


def card_remove_function(params, function):
    if (('post_id' in params and params['post_id']) and
            ('feed_id' in params and params['feed_id']) and
            ('milestone_id' in params and params['milestone_id'])):
        return resp(0, {'error': 'Unauthorized'})
    removed = False
    if 'post_id' in params and params['post_id']:
        card = CardAttributes.objects.filter(post_id=params['post_id'], user_id=params['user_id'], card_attribute=function)
        if card:
            removed = card.delete()[0]
    elif 'feed_id' in params and params['feed_id']:
        card = CardAttributes.objects.filter(feed_id=params['feed_id'], user_id=params['user_id'], card_attribute=function)
        if card:
            removed = card.delete()[0]
    elif 'milestone_id' in params and params['milestone_id']:
        card = CardAttributes.objects.filter(milestone_id=params['milestone_id'], user_id=params['user_id'],
                                             card_attribute=function)
        if card:
            removed = card.delete()[0]
    return resp(0, {'data': removed})


def bookmark_card(request):
    try:
        params = json.loads(request.body)
        card_function(params, 'bookmark')
    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


def unbookmark_card(request):
    try:
        params = json.loads(request.body)
        card_remove_function(params, 'bookmark')
    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))
